﻿using Kingdee.BOS;
using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Orm.DataEntity;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//using static Kingdee.BOS.BTree<TKey, TValue>;

namespace HM
{
    [Description("直接调拨单定时获取51JOB物流信息")]
    public class _51JOB: IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {
            try
            {
                string FID = "", F_RXWU_TEXT5 = "", url = "", Result = "", code = "", courier_code = "", create = "", createurl = "", GetResult = "", Geturl = "",
                DeleteURL = "", ID = "", FENTRYID = "", F_RXWU_Text15 = "", tracking_number = "", checkpoint_date = "", checkpoint_delivery_status="", tracking_detail="";
               
               
                url = "https://api.51tracking.com/v3/trackings/detect";
                createurl = "https://api.51Tracking.com/v4/trackings/create";
                Geturl = "https://api.51tracking.com/v4/trackings/get";
                DeleteURL = "https://api.51Tracking.com/v4/trackings/delete?id=";

                string SQL = "/*dialect*/" + string.Format(@" SELECT T.FID, T.F_RXWU_TEXT6 AS F_RXWU_TEXT5,T.FENTRYID,T.F_RXWU_Text15 FROM T_STK_STKTRANSFERINENTRY T
                LEFT JOIN T_STK_STKTRANSFERIN T1 ON T.FID=T1.FID
                LEFT JOIN T_BD_CUSTOMER T2 ON T1.F_RXWU_Base2=T2.FCUSTID
                LEFT JOIN T_BD_CUSTOMERGROUP_L T3 ON T2.FPRIMARYGROUP=T3.FID
                WHERE T.F_RXWU_TEXT6<>'' AND T3.FNAME='独立站' ");
                DynamicObjectCollection DynamData = DBUtils.ExecuteDynamicObject(ctx, SQL);
                if(DynamData.Count>0)
                {
                    for(int i=0;i<DynamData.Count;i++)
                    {
                        F_RXWU_TEXT5 = Convert.ToString(DynamData[i]["F_RXWU_TEXT5"]);
                        FENTRYID = Convert.ToString(DynamData[i]["FENTRYID"]);
                        F_RXWU_Text15 = Convert.ToString(DynamData[i]["F_RXWU_Text15"]);
                        FID = Convert.ToString(DynamData[i]["FID"]);
                        if (!F_RXWU_Text15.Equals("") && !F_RXWU_Text15.Equals(" "))
                        {
                            //删除单号创建信息
                            DeleteNumber.Delete(F_RXWU_Text15, DeleteURL);
                        }
                        JObject Obj = new JObject();
                        //获取物料商编码
                        Obj.Add("tracking_number", F_RXWU_TEXT5);
                        Result = PostMan.Post(url, Obj.ToString());
                        JObject jobject = JObject.Parse(Result);
                        code = Convert.ToString(jobject["code"]);
                        if (code.Equals("200"))
                        {
                            //获取物料商编码
                            courier_code = Convert.ToString(jobject["data"][0]["courier_code"]);
                            //创建物流商
                            JObject ObjCreate = new JObject();
                            ObjCreate.Add("tracking_number", F_RXWU_TEXT5);
                            ObjCreate.Add("courier_code", courier_code);
                            create = PostMan.Post(createurl, ObjCreate.ToString());
                            JObject jobject0 = JObject.Parse(create);
                            code = Convert.ToString(jobject0["meta"]["code"]);
                            if (code.Equals("200"))
                            {
                                ID = Convert.ToString(jobject0["data"]["id"]);
                                string SQL1 = "/*dialect*/" + string.Format(@"update T_STK_STKTRANSFERINENTRY set F_RXWU_Text15='{1}' where FENTRYID='{0}'", FENTRYID, ID);
                                DBUtils.Execute(ctx, SQL1);
                                //获取物流轨迹
                                Dictionary<string, string> dictionary = new Dictionary<string, string>();
                                dictionary.Add("tracking_numbers", F_RXWU_TEXT5);
                                GetResult = Gettrackings.Get(Geturl, dictionary);
                                JObject jobject1 = JObject.Parse(GetResult);
                                code = Convert.ToString(jobject1["meta"]["code"]);
                                if (code.Equals("200"))
                                {
                                    if (jobject1["data"]["success"].Count() > 0)
                                    {
                                        for (int k = 0; k < jobject1["data"]["success"].Count(); k++)
                                        {
                                            tracking_number = Convert.ToString(jobject1["data"]["success"][k]["tracking_number"]);
                                            courier_code = Convert.ToString(jobject1["data"]["success"][k]["courier_code"]);
                                            //先删除再重新获取轨迹信息
                                            string SQL4 = "/*dialect*/" + string.Format(@"delete from T_SAL_ORDERTRACE where FCARRYBILLNO='{0}'", tracking_number);
                                            DBUtils.Execute(ctx, SQL4);
                                            if (jobject1["data"]["success"][k]["origin_info"]["trackinfo"].Count()>0)
                                            {
                                                for(int n=0;n<jobject1["data"]["success"][k]["origin_info"]["trackinfo"].Count();n++)
                                                {
                                                    checkpoint_date = Convert.ToString(jobject1["data"]["success"][k]["origin_info"]["trackinfo"][n]["checkpoint_date"]);
                                                    checkpoint_delivery_status = Convert.ToString(jobject1["data"]["success"][k]["origin_info"]["trackinfo"][n]["checkpoint_delivery_status"]);
                                                    tracking_detail = Convert.ToString(jobject1["data"]["success"][k]["origin_info"]["trackinfo"][n]["tracking_detail"]);
                                                    var dbFEBTRYID = ((long[])(Kingdee.BOS.ServiceHelper.DBServiceHelper.GetSequenceInt64(ctx, "T_SAL_ORDERTRACE", 1)))[0];
                                                    string SQL2 = "/*dialect*/" + string.Format(@"insert into T_SAL_ORDERTRACE(FENTRYID,FID,FCARRYBILLNO,F_RXWU_Text16,F_RXWU_Text17,F_RXWU_Text18) values({0},{1},{2},'{3}','{4}','{5}')",
                                                     dbFEBTRYID, FID, tracking_number, checkpoint_delivery_status, checkpoint_date, courier_code);
                                                    DBUtils.Execute(ctx, SQL2);
                                                    string SQL3 = "/*dialect*/" + string.Format(@"insert into T_SAL_LOGISTINFODETAIL(FENTRYID,FID,FTRACETIME,FTRACEDETAIL) values('{0}','{1}','{2}','{3}')",
                                                     FID + "-" + "STK_TransferDirect" + dbFEBTRYID + "-" + checkpoint_date, FID + "-" + "STK_TransferDirect" + "-" + dbFEBTRYID, checkpoint_date, tracking_detail);
                                                    DBUtils.Execute(ctx, SQL3);
                                                }
                                            }
                                            #region
                                            //if (tracking_number.Equals(F_RXWU_TEXT5))
                                            //{
                                            //latest_event = Convert.ToString(jobject1["data"]["success"][k]["latest_event"]);
                                            //delivery_status = Convert.ToString(jobject1["data"]["success"][k]["delivery_status"]);
                                            //latest_checkpoint_time = Convert.ToString(jobject1["data"]["success"][k]["latest_checkpoint_time"]);
                                            //courier_code = Convert.ToString(jobject1["data"]["success"][k]["courier_code"]);
                                            //if (!latest_event.Equals("")&&!latest_event.Equals(" "))
                                            //{
                                            //    latest_event = BaiduAPI.GET(latest_event);
                                            //    JObject jobject2 = JObject.Parse(latest_event);
                                            //    latest_event = Convert.ToString(jobject2["trans_result"][0]["dst"]);
                                            //}
                                            //Thread.Sleep(3000);
                                            //if (!delivery_status.Equals("") && !delivery_status.Equals(" "))
                                            //{
                                            //    delivery_status = BaiduAPI.GET(delivery_status);
                                            //    JObject jobject3 = JObject.Parse(delivery_status);
                                            //    delivery_status = Convert.ToString(jobject3["trans_result"][0]["dst"]);
                                            //}
                                            //if (!latest_event.Equals("") && !latest_event.Equals(" "))
                                            //{
                                            //   var dbFEBTRYID = ((long[])(Kingdee.BOS.ServiceHelper.DBServiceHelper.GetSequenceInt64(ctx, "T_SAL_ORDERTRACE", 1)))[0];
                                            //    string SQL2 = "/*dialect*/" + string.Format(@"insert into T_SAL_ORDERTRACE(FENTRYID,FID,FCARRYBILLNO,F_RXWU_Text16,F_RXWU_Text17,F_RXWU_Text18) values({0},{1},{2},'{3}','{4}','{5}')",
                                            //     dbFEBTRYID, FID, tracking_number, delivery_status, latest_checkpoint_time, courier_code);
                                            //    DBUtils.Execute(ctx, SQL2);
                                            //    string SQL3 = "/*dialect*/" + string.Format(@"insert into T_SAL_LOGISTINFODETAIL(FENTRYID,FID,FTRACETIME,FTRACEDETAIL) values('{0}','{1}','{2}','{3}')",
                                            //     FID + "-" + "STK_TransferDirect" + dbFEBTRYID + "-" + latest_checkpoint_time, FID + "-" + "STK_TransferDirect" + "-"+dbFEBTRYID, latest_checkpoint_time, latest_event);
                                            //    DBUtils.Execute(ctx, SQL3);
                                            //}
                                            //}
                                            #endregion
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {

            }
        }
    }
}
